package tk.mynoteapp.dev.demo22.headerapiversion;

import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义SpringMVC请求匹配条件对象
 */
public class APIVersionCondition implements RequestCondition<APIVersionCondition> {
    private String apiVersion;
    private String headerKey;

    public APIVersionCondition(String apiVersion, String headerKey) {
        this.apiVersion = apiVersion;
        this.headerKey = headerKey;
    }

    /**
     * 用户合并其它APIVersionCondition
     * @param other
     * @return
     */
    @Override
    public APIVersionCondition combine(APIVersionCondition other) {
        return new APIVersionCondition(other.getApiVersion(), other.getHeaderKey());
    }

    /**
     * 用于请求匹配：根据headerKey获取请求头中的version和当前apiVersion相同则匹配成功
     * @param request
     * @return
     */
    @Override
    public APIVersionCondition getMatchingCondition(HttpServletRequest request) {
        String version = request.getHeader(headerKey);
        return apiVersion.equals(version) ? this : null;
    }

    @Override
    public int compareTo(APIVersionCondition apiVersionCondition, HttpServletRequest request) {
        return 0;
    }

    public String getApiVersion() {
        return apiVersion;
    }

    public String getHeaderKey() {
        return headerKey;
    }
}
